<?php
/**
 * @Author: Marte
 * @Date:   2020-01-31 19:52:03
 * @Last Modified by:   Marte
 * @Last Modified time: 2020-03-31 22:51:42
 */

//测试使用
function post($key){
    if(isset($_POST[$key])){
        return $key;
    }else{
        return mt_rand(1, 100);
    }
}

//伪代码
function  publish(){
    $user_id = post('user_id');
    $topic_id = post('topic_id');
    $content = post('content');
    //如果没有父级评论ID则传0或空
    $comment_id = post('comment_id');
    //如果是第一层评论直接插入数据
    if(!$comment_id){
        DB::table('comment')->insert([
            'topic_id' => $topic_id,
            'user_id' => $user_id,
            'content' => $content,
            'pid' => 0,
            'level' => 1,
            'line' => 1,
            'created_at' => time(),
        ]);
    }else{
        //如果不是第一层评论，父级评论ID取$comment_id
        $comment = DB::table('comment')->where(['id' => $comment_id])->first();
        //楼层数level加一
        $level = $comment->level + 1;
        //楼层所在位置line取当前楼层最后位置数加一
        $line = DB::table('comment')->where(['topic_id' => $topic_id, 'level' => $level])->value('max(line)');
        DB::table('comment')->insert([
            'topic_id' => $topic_id,
            'user_id' => $user_id,
            'content' => $content,
            'pid' => $comment_id,
            'level' => $level,
            'line' => $line + 1,
            'created_at' => time(),
        ]);
    }
}

function  tree(){
    $user_id = post('user_id');
    $topic_id = post('topic_id');

    //先排好序,查出所有评论
    $comment = DB::table('comment')
        ->where(['topic_id' => $topic_id])
        ->order('level desc, line asc')
        ->get()
        ->toArray();

    //再循环生成树结构
    $list = [];
    foreach ($comment as $key => $val){
        if(isset($comment[$val['pid'] - 1])){
            $comment[$val['pid'] - 1]['children'][] = &$comment[$key];
        }else{
            $list[] = &$comment[$key];
        }
    }

    return $list;
}
